package framework.proxy;

import framework.config.XServiceConfig;
import framework.transport.cluster.Cluster;
import framework.transport.codec.XResponse;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ClientProxy implements InvocationHandler {

    private final XServiceConfig xServiceConfig;

    private final Cluster cluster;

    public ClientProxy(XServiceConfig xServiceConfig, Cluster cluster) {
        this.xServiceConfig = xServiceConfig;
        this.cluster = cluster;
    }

    @SuppressWarnings("unchecked")
    public <T> T getProxy(Class<T> clazz) {
        return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class<?>[]{clazz}, this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        XResponse<Object> response = cluster.remoteCall(proxy, method, args, xServiceConfig);
        return response.getData();
    }
}
